package com.example.java.base.rabbitmq.a1one2one;

import com.example.java.base.rabbitmq.util.RabbitMqUtil;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Consumer:消费消息
 *
 * @author zhangxiaoxiang
 * @date 2020/11/15
 */
public class Consumer {
    public static void main(String[] args) {
        try {
            // 获取connection
            Connection connection = RabbitMqUtil.getConnection();
            // 获取channel
            Channel channel = connection.createChannel();
            // 创建队列 1-队列名称 2-队列是否持久化 3-是否是排他队列 4-使用完之后是否删除此队列 5-其他属性
            channel.queueDeclare("hello", false, false, false, null);
            //消费消息.	1-消费队列	2-是否自动发送消息回执	3-回调函数
            channel.basicConsume("hello", true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
                        throws IOException {
                    String message = new String(body, StandardCharsets.UTF_8);
                    System.out.println("接收到的消息为: " + message);
                }
            });
            System.out.println("消费了消息");
            //    消费端应该处于监听状态,一般不用关闭连接
            // 	channel.close();
            // 	connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}